/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.polarrose.spring.bayeux;

import org.mortbay.cometd.Bayeux;
import org.mortbay.cometd.continuation.ContinuationCometdServlet;

import javax.servlet.ServletException;
import java.util.Map;
import java.util.HashMap;

/**
 * Subclass of Jetty's {@link org.mortbay.cometd.continuation.ContinuationCometdServlet} that keeps track of
 * {@link org.mortbay.cometd.Bayeux} instances and provides a way to look those up by (servlet) name.
 *
 * @author Stefan Arentz
 */

public class BayeuxServlet extends ContinuationCometdServlet
{
    /**
     * Bayeux instances mapped by servlet name.
     */

    private static final Map<String, Bayeux> bayeuxs = new HashMap<String, Bayeux>();

    /**
     * @see org.mortbay.cometd.continuation.ContinuationCometdServlet#init() 
     */

    public void init() throws ServletException
    {
        super.init();

        synchronized(bayeuxs) {
            bayeuxs.put(
                getServletName(),
                (Bayeux) getServletContext().getAttribute(ContinuationCometdServlet.ORG_MORTBAY_BAYEUX)
            );
        }
    }

    /**
     * Return the default {@link org.mortbay.cometd.Bayeux} instance.
     * 
     * @return the default {@link org.mortbay.cometd.Bayeux} instance
     */

    static Bayeux getDefaultBayeux()
    {
        if (bayeuxs.size() == 0) {
            throw new RuntimeException("No BayeuxServlet has been configured");
        }

        if (bayeuxs.size() != 1) {
            throw new RuntimeException("Multiple BayeuxServlet instances configured");
        }

        return bayeuxs.values().iterator().next();
    }

    /**
     * 
     * @param name the name of the {@link com.polarrose.spring.bayeux.BayeuxServlet}
     * @return the {@link org.mortbay.cometd.Bayeux} instance
     */

    static Bayeux getBayeuxByServletName(String name)
    {
        return bayeuxs.get(name);
    }
}
